package model

import (
	"context"
	"fmt"
	"github.com/olivere/elastic/v7"
)

var client *elastic.Client
var host = "http://192.168.4.119:9200"


//初始化
func EsInit() {
	//errorlog := log.New(os.Stdout, "APP", log.LstdFlags)
	var err error
	client, err = elastic.NewClient(elastic.SetSniff(false), elastic.SetURL(host))
	if err != nil {
		panic(err)
	}
	_, _, err = client.Ping(host).Do(context.Background())
	if err != nil {
		panic(err)
	}
	//fmt.Printf("Elasticsearch returned with code %d and version %s\n", code, info.Version.Number)

	_, err = client.ElasticsearchVersion(host)
	if err != nil {
		panic(err)
	}
}



type EsModel struct {
	IndexName string
	TypeName  string
	ID        string
	Body      interface{}

}

func (es *EsModel) Save() {
	//e1 := Employee{"Jane", "Smith", 32, "I like to collect rock albums", []string{"music"}}
	put1, err := client.Index().
		Index(es.IndexName).Type(es.TypeName).Id(es.ID).
		BodyJson(es.Body).Do(context.Background())
	if err != nil {
		panic(err)
	}
	fmt.Printf("Indexed tweet %s to index s%s, type %s\n", put1.Id, put1.Index, put1.Type)

}

func (es *EsModel) update(m map[string]interface{}) {
	res, err := client.Update().Index(es.IndexName).Type(es.TypeName).Id(es.ID).
		Doc(m).Do(context.Background())
	if err != nil {
		println(err.Error())
	}
	fmt.Printf("update age %s\n", res.Result)

}


func (es *EsModel) DeleteById(id string) {

	res, err := client.Delete().Index(es.IndexName).Type(es.TypeName).Id(id).
		Do(context.Background())
	if err != nil {
		println(err.Error())
		return
	}
	fmt.Printf("DeleteById result %s\n", res.Result)
}

func (es *EsModel) FindById(id string) {
	//通过id查找
	getRes, err := client.Get().Index(es.IndexName).Type(es.TypeName).Id(id).Do(context.Background())
	if err != nil {
		panic(err.Error())
	}
	if getRes.Found {
		fmt.Printf("Got document %s in version %d from index %s, type %s\n", getRes.Id, getRes.Version, getRes.Index, getRes.Type)

		es.Body = []byte(getRes.Source)
		//fmt.Println(string(getRes.Source))
	}

}